/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cpal.entrenamiento.controller;

import com.cpal.entrenamiento.controller.util.ElementoMenuTreeNode;
import com.cpal.entrenamiento.entity.ElementoMenu;
import com.cpal.entrenamiento.service.IElaborarMaterialService;
import com.cpal.entrenamiento.service.IPalabraService;
import java.util.LinkedList;
import java.util.List;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.DefaultTreeModel;
import org.zkoss.zul.Tree;
import org.zkoss.zul.TreeModel;
import org.zkoss.zul.TreeNode;

/**
 *
 * @author Omar
 */
public class MenuViewController extends SelectorComposer<Component> {

    private static final long serialVersionUID = 1L;
    private TreeModel<TreeNode<ElementoMenu>> categoriesModel;
    @Wire
    Tree tree;
    @WireVariable
    IElaborarMaterialService elaborarMaterialService;

    public MenuViewController() {
        // construct tree nodes by categories
        ElementoMenu elementoMenuRoot = elaborarMaterialService.obtenerElementos();
        ElementoMenuTreeNode rootNode = contruirArbolTreeNode(elementoMenuRoot);

        // create tree model
        categoriesModel = new DefaultTreeModel<ElementoMenu>(rootNode);
        ((DefaultTreeModel<ElementoMenu>) categoriesModel).addOpenPath(new int[]{0});
    }
    
    private ElementoMenuTreeNode contruirArbolTreeNode(ElementoMenu elemento) {
        ElementoMenuTreeNode menuNode = new ElementoMenuTreeNode(elemento, 0);
        LinkedList<ElementoMenuTreeNode> queue = new LinkedList<ElementoMenuTreeNode>(); // BFS
        queue.add(menuNode);
        while (!queue.isEmpty()) {
            ElementoMenuTreeNode node = queue.remove();
            for (ElementoMenu childCategory : node.getData().getHijos()) {
                ElementoMenuTreeNode child = new ElementoMenuTreeNode(childCategory, 0);
                node.add(child);
                queue.add(child);
            }
        }
        ElementoMenuTreeNode rootNode = new ElementoMenuTreeNode(null, -1); // won't show
        rootNode.add(menuNode);
        return rootNode;
    }

    public TreeModel<TreeNode<ElementoMenu>> getCategoriesModel() {
        return categoriesModel;
    }
//    @Listen("onSelect = #categoriesTree")
//    public void displayCars() {
//        TreeNode<Category> selectedNode = ((DefaultTreeModel<Category>) categoriesModel).getSelection()
//                .iterator().next();
//        Category selectedCategory = selectedNode.getData();
//        List<Car> cars = carService.queryByFilter(selectedCategory.getName());
//        resultGrid.setModel(new ListModelList<Car>(cars));
//    }
}
